<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Voucher extends Public_Controller
{
	public function __construct()
	{
		parent::__construct();
		// Load all the required classes
		$this->load->library('form_validation');
		$this->load->model('stoepje_winners_m');
		$this->load->model('stoepje_vouchers_m');
		$this->load->model('stoepje_prizes_m');
		$this->load->model('stoepje_setting_m');
		$this->load->model('pages_m');
		$this->load->model('page_chunks_m');
		$this->lang->load('voucher', 'dutch');
		$this->load->helper('captcha');
		$this->config->load('voucher');
		$this->_folder = $this->config->item('upload_image_path');
		$this->_path = FCPATH . $this->config->item('upload_image_path');
		// Set the validation rules
		$this->validation_rules = array(
			array(
				'field' => 'code',
				'label' => 'lang:stoepje_voucher_code_title',
				'rules' => 'trim|max_length[8]|min_length[8]|alpha_numeric|required|callback__check_code'
			),
			array(
				'field' => 'description',
				'label' => 'lang:stoepje_voucher_description_title',
				'rules' => 'trim|max_length[255]|required'
			),
			array(
				'field'	=> 'prize_id',
				'label'	=> 'lang:stoepje_voucher_prize_title'
			),
			array(
				'field' => 'status',
				'label' => 'lang:stoepje_voucher_status_title'
			)
		);

		$this->data->prizeList = array();
		if ($prizes = $this->stoepje_prizes_m->order_by('id')->get_all())
		{
			foreach ($prizes as $prize)
			{
				$this->data->prizeList[$prize->id] = $prize->name;
			}
		}
		$this->data->statusList = array(
			'1'		=> lang('stoepje_voucher_status_active_title'),
			'0'		=> lang('stoepje_voucher_status_inactive_title')	
		);
		date_default_timezone_set('Europe/Amsterdam');
		//date_default_timezone_set('Asia/Ho_Chi_Minh');
		
		$this->template->append_metadata(js('jquery.form.js', 'voucher'))
						->append_metadata(js('stoepje.voucher.frontend.js', 'voucher'))
						->append_metadata(css('stoepje.voucher.frontend.css', 'voucher'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		//set the base/default where clause
		$base_where = array();

		//add post values to base_where if f_module is posted
		$base_where = $this->input->post('f_prize') ? $base_where + array('f_prize' => $this->input->post('f_prize')) : $base_where;
		$base_where = $this->input->post('f_status') != '' ? $base_where + array('f_status' => $this->input->post('f_status')) : $base_where;
		$base_where = $this->input->post('f_keywords') ? $base_where + array('keywords' => $this->input->post('f_keywords')) : $base_where;

		// Create pagination links
		$total_rows = $this->stoepje_vouchers_m->count_by($base_where);
		$pagination = create_pagination('admin/news/index', $total_rows);

		// Using this data, get the relevant results
		$vouchers = $this->stoepje_vouchers_m->limit($pagination['limit'])->get_many_by($base_where);

		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';

		$pageTopLeft = $this->pages_m->get_by('meta_title', 'top-left-text');
		if($pageTopLeft){
			$pageChunksTopLeft = $this->page_chunks_m->order_by('sort', 'asc')->get_many_by('page_id', $pageTopLeft->id);
		}else{
			$pageChunksTopLeft = null;
		}
		
		$pageTopRight = $this->pages_m->get_by('meta_title', 'top-right-text');
		if($pageTopRight){
			$pageChunksTopRight = $this->page_chunks_m->order_by('sort', 'asc')->get_many_by('page_id', $pageTopRight->id);
		}else{
			$pageChunksTopRight = null;
		}
		
		$pageBottomBox1 = $this->pages_m->get_by('meta_title', 'bottom-box1-text');
		if($pageBottomBox1){
			$pageChunksBottomBox1 = $this->page_chunks_m->order_by('sort', 'asc')->get_many_by('page_id', $pageBottomBox1->id);
		}else{
			$pageChunksBottomBox1 = null;
		}
		
		$pageBottomBox2 = $this->pages_m->get_by('meta_title', 'bottom-box2-text');
		if($pageBottomBox2){
			$pageChunksBottomBox2 = $this->page_chunks_m->order_by('sort', 'asc')->get_many_by('page_id', $pageBottomBox2->id);
		}else{
			$pageChunksBottomBox2 = null;
		}
		
		$pageBottomBox3 = $this->pages_m->get_by('meta_title', 'bottom-box3-text');
		if($pageBottomBox3){
			$pageChunksBottomBox3 = $this->page_chunks_m->order_by('sort', 'asc')->get_many_by('page_id', $pageBottomBox3->id);
		}else{
			$pageChunksBottomBox3 = null;
		}
		$pageBottomBox4 = $this->pages_m->get_by('meta_title', 'bottom-box4-text');
		if($pageBottomBox4){
			$pageChunksBottomBox4 = $this->page_chunks_m->order_by('sort', 'asc')->get_many_by('page_id', $pageBottomBox4->id);
		}else{
			$pageChunksBottomBox4 = null;
		}
		
		$this->template
			->title($this->module_details['name'])
			//->append_metadata(js('admin/filter.js'))
			->set('captchaWord', $this->_rand_string())
			->set('pageTopLeft', $pageTopLeft)
			->set('pageChunksTopLeft', $pageChunksTopLeft)
			->set('pageTopRight', $pageTopRight)
			->set('pageChunksTopRight', $pageChunksTopRight)
			->set('pageBottomBox1', $pageBottomBox1)
			->set('pageChunksBottomBox1', $pageChunksBottomBox1)
			->set('pageBottomBox2', $pageBottomBox2)
			->set('pageChunksBottomBox2', $pageChunksBottomBox2)
			->set('pageBottomBox3', $pageBottomBox3)
			->set('pageChunksBottomBox3', $pageChunksBottomBox3)
			->set('pageBottomBox4', $pageBottomBox4)
			->set('pageChunksBottomBox4', $pageChunksBottomBox4)
			->set('pagination', $pagination)
			->set('vouchers', $vouchers);

		$this->input->is_ajax_request() ? $this->template->build('index', $this->data) : $this->template->build('index', $this->data);
	}
	
	public function submit()
	{
		/*
		$captcha = $this->input->post('captcha');
		$correctCaptcha 	= $this->session->userdata('captcha_content');
		$expTime			= $this->session->userdata('captcha_exprise_time');
		*/
		$code = $this->input->post('code');
		$salutation = $this->input->post('salutation');
		$firstName = $this->input->post('first_name');
		$lastName = $this->input->post('last_name');
		$postcode = $this->input->post('postcode');
		$email = $this->input->post('email');
		$accept = $this->input->post('accept');
		
		$this->load->helper('email');
		
		$errorMessage = '';
		$oneEurePrize = false;
		$voucher = null;
		$prize = null;
		/*
		if( $correctCaptcha != $captcha){
			$errorMessage = lang('stoepje_winner_frontend_code_invalid_captcha');
		}else if( time() > $expTime ){
			$errorMessage = lang('stoepje_winner_frontend_code_captcha_expired');
		}else 
		*/
		if($code == ""){
			$errorMessage = lang('stoepje_winner_frontend_code_required_error');
		}else if($firstName == ""){
			$errorMessage = lang('stoepje_winner_frontend_first_name_required_error');
		}else if($lastName == ""){
			$errorMessage = lang('stoepje_winner_frontend_last_name_required_error');
		}else if($postcode == ""){
			$errorMessage = lang('stoepje_winner_frontend_postcode_required_error');
		}else if($email == ""){
			$errorMessage = lang('stoepje_winner_frontend_email_required_error');
		}else if(!valid_email($email)){
			$errorMessage = lang('stoepje_winner_frontend_email_invalid_error');
		}else if(!$accept){
			$errorMessage = lang('stoepje_winner_frontend_accept_required_error');
		}
		if(!$errorMessage){
			$voucher = $this->stoepje_vouchers_m->where('status', 0)->get_by('code', $code);
			
			if($voucher){
				$ticketPrizeId = 1;
				$activeSetting = $this->stoepje_setting_m->getByKey('active_setting');
				if($activeSetting->value){
					$fromTime = $this->stoepje_setting_m->getByKey('from_time');
					$toTime = $this->stoepje_setting_m->getByKey('to_time');
					$numberOfWinner = $this->stoepje_setting_m->getByKey('number_of_winner');
					$fromTimeValue = strtotime(date('j') . '-' . date('n') . '-'. date('Y') . ' 0:0:0');
					$toTimeValue = strtotime(date('j') . '-' . date('n') . '-'. date('Y') . ' 23:59:0');
					$ticketWinnerNumber = $this->stoepje_winners_m->count_by_prize($ticketPrizeId, $fromTimeValue, $toTimeValue);

					if(time() > $fromTime->value && time() < $toTime->value && $numberOfWinner->value > $ticketWinnerNumber){
						$this->stoepje_vouchers_m->update($voucher->id, array('prize_id' => $ticketPrizeId));
						$voucerReplace = $this->stoepje_vouchers_m->getByPrizeId($ticketPrizeId);
						if($voucerReplace){
							$this->stoepje_vouchers_m->update($voucerReplace->id, array('prize_id' => 8));
						}
						$prize = $this->stoepje_prizes_m->get($ticketPrizeId);
						if($prize){
							$this->stoepje_winners_m->insert(array(
								'code'				=> $code,
								'salutation'		=> $salutation,
								'first_name'		=> $firstName,
								'last_name'			=> $lastName,
								'postcode'			=> $postcode,
								'email'				=> $email,
								'prize_id'			=> $prize->id,
								'prize_name'		=> $prize->name,
								'ip'				=> $this->input->ip_address(),
								'submit_time'		=> time()
							));
							
							$this->stoepje_vouchers_m->update($voucher->id, array(
								'status' 		=> 1
							));
							
							$this->load->library('settings');
							$this->load->library('email');
							$this->email->from($sendEmail = $this->settings->get('server_email'), lang('stoepje_winner_frontend_email_name_label'));
							$this->email->to($email);
							$this->email->subject(lang('stoepje_winner_frontend_email_subject_label'));
							$prize->email = str_replace('###SALUTATION###', lang('stoepje_winner_salutation_'.$salutation), $prize->email);
							$prize->email = str_replace('###FIRSTNAME###', $firstName, $prize->email);
							$prize->email = str_replace('###LASTNAME###', $lastName, $prize->email);
							$prize->email = str_replace('###VOUCHERCODE###', $voucher->code, $prize->email);
							$this->email->message($prize->email);
							if($prize->id != 8){
								$this->email->send();
							}
						}else{
							$oneEurePrize = true;
						}
					}else{
						$prize = $this->stoepje_prizes_m->get($voucher->prize_id);
						if($prize){
							$this->stoepje_winners_m->insert(array(
								'code'				=> $code,
								'salutation'		=> $salutation,
								'first_name'		=> $firstName,
								'last_name'			=> $lastName,
								'postcode'			=> $postcode,
								'email'				=> $email,
								'prize_id'			=> $prize->id,
								'prize_name'		=> $prize->name,
								'ip'				=> $this->input->ip_address(),
								'submit_time'		=> time()
							));
							
							$this->stoepje_vouchers_m->update($voucher->id, array(
								'status' 		=> 1
							));
							
							$this->load->library('settings');
							$this->load->library('email');
							$this->email->from($sendEmail = $this->settings->get('server_email'), lang('stoepje_winner_frontend_email_name_label'));
							$this->email->to($email);
							$this->email->subject(lang('stoepje_winner_frontend_email_subject_label'));
							$prize->email = str_replace('###SALUTATION###', lang('stoepje_winner_salutation_'.$salutation), $prize->email);
							$prize->email = str_replace('###FIRSTNAME###', $firstName, $prize->email);
							$prize->email = str_replace('###LASTNAME###', $lastName, $prize->email);
							$prize->email = str_replace('###VOUCHERCODE###', $voucher->code, $prize->email);
							$this->email->message($prize->email);
							if($prize->id != 8){
								$this->email->send();
							}
						}else{
							$oneEurePrize = true;
						}
					}
					
				}else{
					$prize = $this->stoepje_prizes_m->get($voucher->prize_id);
					if($prize){
						$this->stoepje_winners_m->insert(array(
							'code'				=> $code,
							'salutation'		=> $salutation,
							'first_name'		=> $firstName,
							'last_name'			=> $lastName,
							'postcode'			=> $postcode,
							'email'				=> $email,
							'prize_id'			=> $prize->id,
							'prize_name'		=> $prize->name,
							'ip'				=> $this->input->ip_address(),
							'submit_time'		=> time()
						));
						
						$this->stoepje_vouchers_m->update($voucher->id, array(
							'status' 		=> 1
						));
						
						$this->load->library('settings');
						$this->load->library('email');
						$this->email->from($sendEmail = $this->settings->get('server_email'), lang('stoepje_winner_frontend_email_name_label'));
						$this->email->to($email);
						$this->email->subject(lang('stoepje_winner_frontend_email_subject_label'));
						$prize->email = str_replace('###SALUTATION###', lang('stoepje_winner_salutation_'.$salutation), $prize->email);
						$prize->email = str_replace('###FIRSTNAME###', $firstName, $prize->email);
						$prize->email = str_replace('###LASTNAME###', $lastName, $prize->email);
						$prize->email = str_replace('###VOUCHERCODE###', $voucher->code, $prize->email);
						$this->email->message($prize->email);
						if($prize->id != 8){
							$this->email->send();
						}
					}else{
						$oneEurePrize = true;
					}
				}
			}else{
				$errorMessage = lang('stoepje_winner_frontend_no_existed_code_error');
			}
		}
		
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
		$this->data->imagePath = $this->_path;
		$this->data->imageFolder = $this->_folder;
		$this->data->errorMessage = $errorMessage;
		$this->data->oneEurePrize = $oneEurePrize;
		$this->data->voucher = $voucher;
		$this->data->prize = $prize;
		$content = $this->load->view('result', $this->data, TRUE);

		return $this->template->build_json(array(
			'status'	=> $errorMessage? false: true,
			'content'	=> $content
		));
		/*
		$this->template
			->set('imagePath', $this->_path)
			->set('imageFolder', $this->_folder)
			->set('errorMessage', $errorMessage)
			->set('oneEurePrize', $oneEurePrize)
			->set('voucher', $voucher)
			->set('prize', $prize)
			->build('result', $this->data);
		*/
	}
	
	private function _rand_string($length = 5)
	{
		$chars = 'ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz';
		$max = strlen($chars)-1;
		$string = '';
		mt_srand((double)microtime() * 1000000);
		while (strlen($string) < $length)
		{
			$string .= $chars{mt_rand(0, $max)};
		}
		return $string;
	}
	
	public function term_of_use(){
		$page = $this->pages_m->get_by('slug', 'term-of-use');
		$pageChunks = $this->page_chunks_m->order_by('sort', 'asc')->get_many_by('page_id', $page->id);
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
		$this->template
			->set('pageChunks', $pageChunks)
			->build('term_of_use', $this->data);
	}
	public function refesh_captcha(){
		$captchaWord = $this->_rand_string();
		$vals = array(
		    'word' => $captchaWord,
		    'img_path' => './uploads/default/captcha/',
		    'img_url' => site_url().'uploads/default/captcha/',
		    'font_path' => './uploads/default/captcha/fonts/TimesNewRomanBold.ttf',
		    'img_width' => '150',
		    'img_height' => 30,
		    'expiration' => 7200
		    );
		$timeLIMIT = 720;
		$captcha = array( 'captcha_exprise_time'=>time() + $timeLIMIT , 'captcha_content'=>$captchaWord );
		$ci = &get_instance();
		$ci->session->set_userdata($captcha);
		$cap = create_captcha($vals);
		
		$result = array();
		$result['result'] = true;
		$result['data'] = $cap['image'];
		echo json_encode($result);
	}
}
